package com.yang.thread.wait;

import java.util.Vector;

/**
 * @author yds
 * @program thread-study
 * @description 线程等待唤醒
 * @create 2020-10-28 15:16
 **/
public class ThreadWaitNotifyTest {
    public static void main(String args[]) {
        Vector obj = new Vector();
        Thread consumer = new Thread(new Consumer(obj));
        Thread producter = new Thread(new Producter(obj));
        consumer.start();
        producter.start();
    }
}
/**
 * 作为消费者不断消费
 */
class Consumer implements Runnable {
    private Vector obj;
    public Consumer(Vector v) {
        this.obj = v;
    }
    public void run() {
        synchronized(obj) {
            while (true) {
                try {
                    if (obj.size() ==0){
                        obj.wait();
                    }
                    obj.clear();
                    System.out.println("消费者:苹果我拿了"+"，篮子里有"+obj.size()+"个苹果");
                    obj.notify();
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * 作为生产者不断生产苹果
 */
class Producter implements Runnable {
    private Vector obj;
    public Producter(Vector v) {
        this.obj = v;
    }
    public void run() {
        synchronized(obj) {
            while (true) {
                try {
                    if (obj.size() !=0){
                        obj.wait();
                    }
                    obj.add(new String("apples"));
                    obj.notify();
                    System.out.println("生产者：我又放了一个苹果"+"，篮子有"+obj.size()+"个苹果");
                    Thread.sleep(500);
                }
                catch(Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}